#include <time.h>
#include <stdio.h>
#include <pspsdk.h>
#include <string.h>
#include <psputils.h>
#include <pspkernel.h>
#include <pspdisplay.h>
#include <pspiofilemgr.h>

PSP_MODULE_INFO("ABC", 0, 1, 1);
PSP_MAIN_THREAD_ATTR(0);
PSP_HEAP_SIZE_KB(200);

int FileNum = 0;
char PicPath[256];

static int GetRandomNum(int lo, int hi)
{	
	SceKernelUtilsMt19937Context ctx;
	sceKernelUtilsMt19937Init(&ctx, time(NULL));
	u32 rand_val = sceKernelUtilsMt19937UInt(&ctx);
	rand_val = lo + rand_val % hi;
	return (int)rand_val;
}

void CopyFile(char* src, char* dst)
{
	u8* buffer;
	int bsize = 190000;
	int r = bsize;
	int k;

	k = pspSdkSetK1(0);
	buffer = new u8[bsize];

	int f1 = sceIoOpen(src, PSP_O_RDONLY, 077);
	if(f1 < 0) {delete buffer; pspSdkSetK1(k); return;}

	int f2 = sceIoOpen(dst, PSP_O_WRONLY | PSP_O_CREAT | PSP_O_TRUNC, 0777);

	while (r == bsize)
	{
		r = sceIoRead(f1, buffer, bsize);
		sceIoWrite(f2, buffer, r);
	}

	sceIoClose(f1);
	sceIoClose(f2);

	pspSdkSetK1(k);
	delete buffer;
}

int main_thread(SceSize args, void *argp) {
	sceKernelDelayThread(2000000);
	FileNum = GetRandomNum(11, 30);
	sprintf(PicPath, "ms0:/PICTURE/BGC/%d.bmp", FileNum);
	sceIoRemove("flash1:/vsh/theme/wallpaper.bmp");
	CopyFile(PicPath, "flash1:/vsh/theme/wallpaper.bmp");  
	sceKernelDelayThread(3000000);
	sceKernelExitDeleteThread(0);
	return 0;
} 

int module_start(SceSize args, void *argp) {
	int thid;
	int r;
	thid = sceKernelCreateThread("ABC", main_thread, 0x18, 0x1000, 0, NULL);
	if(thid >= 0) r = sceKernelStartThread(thid, args, argp);
	sceKernelWaitThreadEnd(r, 0);
	return 0;
}